#  Copyright (c) 2023. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
#  Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
#  Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
#  Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
#  Vestibulum commodo. Ut rhoncus gravida arcu.

# coding:utf8
import re
from functools import partial

from PyQt5.QtCore import QObject, pyqtSignal, QSize
from PyQt5.QtWidgets import QListWidget, QPushButton, QListWidgetItem
from log import logger

from project import Card, IP


class ProxyListWidget(QObject):
    btnClickSignal = pyqtSignal(str)
    
    def __init__(self, listwidget: QListWidget, parent=None):
        super(ProxyListWidget, self).__init__()
        
        # text: [点击查找 [4] 网段IP]
        self.btn_texts = []
        self.parent = parent
        self.ListWidget = listwidget
    
    def create_items_from_card(self, card: Card):
        """
        向ListWidget添加所有的项,带btn控件;
        """
        ips_list = card.ips()
        
        if ips_list:
            self.ListWidget.clear()
            self.btn_texts = []
        
        for ip_str in ips_list:
            self.add_section(ip_str)
    
    def add_section(self, ip_str):
        """
        ListWidget , 跟据IP字段, 添加一行(项)
        """
        if IP.check_ip_formatter(ip_str) is None:
            return
        
        ipobj = IP(ip_str)
        text = "点击查看[ {} ]网段在线状态"
        text = text.format(ipobj.section())
        self.btn_texts.append(text)
        self.__create_item(text)
        logger.debug("ListWidget add item, text is {}".format(text))
    
    def __remove_current_items(self):
        """
        删除当前选中的一行;
        未使用
        """
        index = self.ListWidget.currentIndex()
        item_text = self.ListWidget.currentItem().text()
        row = index.row()
        self.ListWidget.takeItem(row)
        self.btn_texts.remove(str(item_text))
        logger.info("ListWidget take current item: {}".format(item_text))
    

    
    def __create_item(self, btn_text):
        """
        跟据 提供的文本 向ListWidget添加一行;
        """
        btn = QPushButton(btn_text, self.parent)
        # 左对齐
        btn.setStyleSheet("QPushButton{text-align: left;}")
        item = QListWidgetItem()
        item.setSizeHint(QSize(335, 40))
        self.ListWidget.addItem(item)
        self.ListWidget.setItemWidget(item, btn)
        
        # 连接按钮的槽
        btn.clicked.connect(partial(self.on_click, btn_text))
    
    @staticmethod
    def __analy_item_text(text: str):
        """
        解析如下格式的文字
       `点击查找 [{}] 网段的IP`
       :return
            ip->section <str>
        """
        match = re.search(r"\d+", text)
        if match:
            return match.group()
    
    def on_click(self, btn_text):
        """
        列表中每个按钮共有的槽函数;
        """
        logger.debug("slot param is: {}".format(btn_text))
        tsr = ""
        section = self.__analy_item_text(btn_text)
        self.btnClickSignal.emit(section)
        self.set_btn_status(False)
        
    
    def set_btn_status(self, b_enable = True):
        """
        b_enable: True 默认
        设置btn的状态
        """
        b_enable = bool(b_enable)
        count_ = self.ListWidget.count()
        for row in range(count_):
            item = self.ListWidget.item(row)
            btn = self.ListWidget.itemWidget(item)
            btn.setEnabled(b_enable)